package avicit.bdp.dgs.metadata.service;

import avicit.bdp.common.base.BaseService;
import avicit.bdp.common.utils.BdpLogUtil;
import avicit.bdp.common.utils.CheckParaUtils;
import avicit.bdp.core.constant.Constants;
import avicit.bdp.core.util.json.JSONUtils;
import avicit.bdp.dgs.metadata.dao.MetadataModelAttributeDao;
import avicit.bdp.dgs.metadata.dto.MetadataModelAttributeDTO;
import avicit.bdp.dgs.metadata.dto.OptionAttribute;
import avicit.platform6.commons.utils.ComUtil;
import avicit.platform6.core.properties.PlatformConstant;
import avicit.platform6.core.rest.msg.QueryRespBean;
import com.github.pagehelper.Page;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 元模型属性服务层
 *
 * @author mayi
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class MetadataModelAttributeService
    extends BaseService<MetadataModelAttributeDao, MetadataModelAttributeDTO> {

  @Resource private MetadataModelAttributeDao metadataModelAttributeDao;

  @Transactional(readOnly = true)
  public QueryRespBean<MetadataModelAttributeDTO> getPageList(
      String metadataModelId, String keyWords, Integer type, Integer pageNo, Integer pageSize)
      throws Exception {

    CheckParaUtils.checkStringValidity(metadataModelId, logger, "元模型ID必填");
    CheckParaUtils.checkIntegerValidity(type, logger, "类型必填");

    QueryRespBean<MetadataModelAttributeDTO> queryRespBean = new QueryRespBean<>();

    List<Integer> typeList = new ArrayList<>();
    // type 属性分类[1技术属性，2业务属性]

    if (MetadataModelAttributeDTO.TYPE_TECH == type) {
      typeList.add(1);
    } else if (MetadataModelAttributeDTO.TYPE_BUS == type) {
      typeList.add(2);
      typeList.add(3);
    }

    com.github.pagehelper.PageHelper.startPage(pageNo, pageSize);
    Page<MetadataModelAttributeDTO> page =
        metadataModelAttributeDao.getPageList(metadataModelId, keyWords, typeList);
    for (MetadataModelAttributeDTO item : page.getResult()) {
      if (StringUtils.isNotEmpty(item.getOptionAttribute())) {
        item.setOptionAttributeList(
            JSONUtils.toList(item.getOptionAttribute(), OptionAttribute.class));
      }
    }
    queryRespBean.setResult(page);
    return queryRespBean;
  }

  public String save(MetadataModelAttributeDTO dto) {
    CheckParaUtils.checkStringValidity(dto.getMetadataModelId(), logger, "元模型ID必填");

    dto.setId(ComUtil.getId());
    dto.setVersion(1L);

    if (CollectionUtils.isNotEmpty(dto.getOptionAttributeList())) {
      dto.setOptionAttribute(JSONUtils.toJsonString(dto.getOptionAttributeList()));
    }

    this.insertWithoutVersion(dto);
    log4Insert(dto);

    return dto.getId();
  }

  public void update(MetadataModelAttributeDTO dto) {

    CheckParaUtils.checkStringValidity(dto.getMetadataModelId(), logger, "元模型ID必填");

    MetadataModelAttributeDTO oldMetadataModelAttributeDTO = this.selectByPrimaryKey(dto.getId());
    CheckParaUtils.checkDbObjectValidity(
        oldMetadataModelAttributeDTO, logger, String.format("没有查到数据，请确保id:%s的数据是否存在", dto.getId()));
    dto.setCreationDate(oldMetadataModelAttributeDTO.getCreationDate());

    if (CollectionUtils.isNotEmpty(dto.getOptionAttributeList())) {
      dto.setOptionAttribute(JSONUtils.toJsonString(dto.getOptionAttributeList()));
    }

    this.updateByPrimaryKey(dto);
    BdpLogUtil.log4Update(dto, oldMetadataModelAttributeDTO);
  }

  public Boolean batchDelete(String ids) {
    CheckParaUtils.checkStringValidity(ids, logger, "没有传入待删除的ID");
    String[] idArr = ids.split(Constants.COMMA);
    for (String id : idArr) {
      MetadataModelAttributeDTO metadataModelAttributeDTO = this.selectByPrimaryKey(id);
      CheckParaUtils.checkDbObjectValidity(
          metadataModelAttributeDTO, logger, String.format("没有查到数据，请确保id:%s的数据是否存在", id));

      this.mapper.deleteByPrimaryKey(id);
      // 记录日志
      BdpLogUtil.log4Delete(metadataModelAttributeDTO);
    }
    return true;
  }

  public MetadataModelAttributeDTO queryById(String id) {
    MetadataModelAttributeDTO metadataModelAttributeDTO = this.selectByPrimaryKey(id);
    CheckParaUtils.checkDbObjectValidity(
        metadataModelAttributeDTO, logger, String.format("没有查到数据，请确保id:%s的数据是否存在", id));
    if (StringUtils.isNotEmpty(metadataModelAttributeDTO.getOptionAttribute())) {
      metadataModelAttributeDTO.setOptionAttributeList(
          JSONUtils.toList(metadataModelAttributeDTO.getOptionAttribute(), OptionAttribute.class));
    }
    return metadataModelAttributeDTO;
  }

  public Boolean changeStatus(String id, Integer validFlag) {
    Boolean flag = this.mapper.changeStatus(id, validFlag) > 0;
    MetadataModelAttributeDTO metadataModelAttributeDTO = this.mapper.selectByPrimaryKey(id);
    // 记录日志
    String logTitle = "";
    if (validFlag == 1) {
      logTitle = "启用元模型属性：【";
    } else {
      logTitle = "停用元模型属性：【";
    }
    logTitle += metadataModelAttributeDTO.getAttributeName() + "】";
    BdpLogUtil.log("元模型模块", logTitle, PlatformConstant.OpType.update);
    return flag;
  }

  public List<MetadataModelAttributeDTO> getListByDatasourceAndType(
      String datasourceType, List<String> businessCodeList) {
    return this.mapper.getListByDatasourceAndType(datasourceType, businessCodeList);
  }
}
